import React, {useEffect, useState, useRef, useCallback} from 'react';
import * as echarts from 'echarts';
import moment from 'moment';
import { useSelector } from 'react-redux';
import axios from 'axios';

const Left1 = (callback, deps) => {
    const [monitorData, setMonitorData] = useState([]);
    const chartRef = useRef(null);
    const ed = useSelector((state) => state.ed);

    useEffect(() => {
        loadMonitorData();
        const chartInstance = echarts.init(chartRef.current);
        updateChart(chartInstance);

        return () => {
            chartInstance.dispose();
        };
        // eslint-disable-next-line no-use-before-define
    }, [loadMonitorData, monitorData, updateChart]);

    useEffect(() => {
        const fetchData = async () => {
            await loadMonitorData();
            const chartInstance = echarts.init(chartRef.current);
            updateChart(chartInstance);
        };
        fetchData().then(r => {});
        // eslint-disable-next-line no-use-before-define
    }, [ed, loadMonitorData, updateChart]);

    const loadMonitorData = useCallback(async () => {
        const url = "/dashboard/pageQueryTodayData";
        const params = {
            page: 1,
            pageSize: 20,
            ...ed
        };
        const resp = await axios.get(url, {params});
        const data = resp.data.list.map(item => ({
            time: moment(item.insert_time).format('hh:mm'),
            value: +item.temperature
        }));
        setMonitorData(data);
    }, [ed]);

    // eslint-disable-next-line react-hooks/exhaustive-deps
    const updateChart = useCallback((chartInstance) => {
        const option = {
            xAxis: {
                type: 'category',
                data: monitorData.map(item => item.time),
                axisLabel: {
                    rotate: -45,
                    margin: 10,
                    color: 'white',
                    fontFamily: 'TencentSans',
                    fontSize: 16
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    color: 'white',
                    fontFamily: 'TencentSans',
                    fontSize: 16
                }
            },
            series: [{
                data: monitorData.map(item => item.value),
                type: 'line',
                lineStyle: {
                    color: 'linear-gradient(0, #D1D1FF, #7C82EA)'
                },
                itemStyle: {
                    color: '#7C82EA'
                }
            }],
            backgroundColor: '#333'
        };
        chartInstance.setOption(option);
    });

    return (
        <div ref={chartRef} style={{ height: '95%' }}></div>
    );
};

export default Left1;
